package com.zdp.rocketmq;

import com.zdp.domain.BonusEventLog;
import com.zdp.domain.User;
import com.zdp.domain.message.UserAddBonusMsgDTO;
import com.zdp.mapper.BonusEventLogMapper;
import com.zdp.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author sesshomaru
 * @date 2021/10/10 18:41
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "consumer-group", topic = "add-bonus-topic")
public class AddBonusListener implements RocketMQListener<UserAddBonusMsgDTO> {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BonusEventLogMapper bonusEventLogMapper;

    @Override
    public void onMessage(UserAddBonusMsgDTO message) {
        // 当收到消息的时候，执行的业务
        // 1. 为用户加积分
        Integer userId = message.getUserId();
        User user = userMapper.selectById(userId);
        Integer bonus = message.getBonus();
        // 新增积分
        user.setBonus(user.getBonus() + message.getBonus());
        userMapper.updateById(user);
        // 2. 记录日志到bonus_event_log表
        this.bonusEventLogMapper.insert(
                BonusEventLog.builder()
                        .userId(userId)
                        .value(bonus)
                        .event("投稿事件")
                        .createTime(LocalDateTime.now())
                        .description("投稿加积分...")
                        .build());

        log.info("积分添加完毕...");
    }
}
